<?php

namespace app\admin\controller;

use app\BaseController;
use think\App;
use think\facade\Db;

/**
 * @author xjw
 * @class:TaskProduct 定时任务=>产品操作
 * @method:product 拉取商品  45分钟执行
 * @method:deal_product 处理商品相关
 * @return  
 */


class Facebook extends BaseController
{

    protected $model = null;
    protected $token = '';
    protected $client_id = '';
    protected $client_secret = '';
    protected $token2 = '';
    protected $client_id2 = '';
    protected $client_secret2 = '';
    protected $token3 = '';
    protected $client_id3 = '';
    protected $client_secret3 = '';
    
    public function __construct(App $app)
    {
        parent::__construct($app);
        
        $fb_token = Db::name('fb_token')->order("id desc")->find();
        $this->token = $fb_token['access_token'];
        $this->client_id = '3372259229753695';
        $this->client_secret = '26cd387d70fb6cef4812afd0164992cf';

        $this->token2 = 'EAAZAGLelrcSkBO1hfTFnWfUrgjXBZB0OLWbx52AWTIRWWAGpdOUGTW4laQPZA9ApODICNrqd0lEJnDeQrVxarDEiXwrcCIBIZAT8HZBtZB2XZAM1D9BCkBsfdVMhepIVEfFl3Vw03KfoIYmoQZB78Y4brpcMZCBlZBHKyLv1ufbkZA2iFv1wnAk1LdFk1KH';
        $this->client_id2 = '1766012863869225';
        $this->client_secret2 = '0b36ddafef946129b0fd92898549ea0b';
        
        $this->token3 = 'EAAOjczIAJosBO0qQqJ2bP83ZAMzqBsZAtdbUEpLkJUVHBSIBa76fnIid9FrTad037zBEgUNT2DjiEOPl2bnrRdXvBDGMNDxXjctTK0RIbO4mQCRZBfhV45emHsajCGrfJyAZB2iCLnI44xaYfpQD5C4jJMZC4DRquu6tMTEAPhONXOTDutTUt9ZBau';
        $this->client_id3 = '1024140085569163';
        $this->client_secret3 = 'cedb3303a2044e1f61fafc07381b3504';
    }

    public function access_token()
    {
        $url = 'https://graph.facebook.com/v18.0/oauth/access_token?grant_type=fb_exchange_token&client_id='.$this->client_id.'&client_secret='.$this->client_secret.'&fb_exchange_token='.$this->token;
        $result = $this->geturl($url);
        $arr = array();
        $arr['result'] = $result;
        $arr['time'] = time();
        $result = json_decode($result,true);
        if(!empty($result['access_token'])){
            $arr['access_token'] = $result['access_token'];
        }
        Db::name('fb_token')->insert($arr);
        return success('操作成功',$result);
    }

    public function advertising()
    {
        $type = 0;
        $where = array();
        $advplat_id = $this->request->request('advplat_id');
        if (!empty($advplat_id)) {
            $where['id'] = $advplat_id;
        }
        $result = array();
        $advplat = Db::name('advplat')
            ->where($where)
            ->where('adv_id',1)
            ->where('status','正常')
            ->order('updatetime asc')
            ->find();
        if($advplat){
            $result = $this->advertising_info($advplat,$type);
            $updatetime['updatetime'] = time();
            Db::name('advplat')
                ->where('id',$advplat['id'])
                ->update($updatetime);
        }
        return success('操作成功',$result);
    }

    public function advertising_yesterday()
    {
        $type = 1;
        $where = array();
        $advplat_id = $this->request->request('advplat_id');
        if (!empty($advplat_id)) {
            $where['id'] = $advplat_id;
        }
        $result = array();
        $advplat = Db::name('advplat')
            ->where($where)
            ->where('adv_id',1)
            ->where('status','正常')
            ->order('updatetime_yesterday asc')
            ->find();
        if($advplat){
            $result = $this->advertising_info($advplat,$type);
            $updatetime_yesterday['updatetime_yesterday'] = time();
            Db::name('advplat')
                ->where('id',$advplat['id'])
                ->update($updatetime_yesterday);
        }
        return success('操作成功',$result);
    }

    public function advertising_automatic()
    {
        $type = 2;
        $where = array();
        $advplat_id = $this->request->request('advplat_id');
        if (!empty($advplat_id)) {
            $where['id'] = $advplat_id;
        }
        $result = array();
        $advplat = Db::name('advplat')
            ->where($where)
            ->where('adv_id',1)
            ->where('status','正常')
            ->order('updatetime_automatic desc')
            ->find();
        if($advplat){
            if(!empty($advplat['updatetime_automatic']) && strtotime($advplat['updatetime_automatic']) > 1672502400){
                if(!empty($advplat['updatetime_automatic'])){
                    $updatetime_automatic['updatetime_automatic'] = date('Y-m-d', strtotime($advplat['updatetime_automatic'])- 24 * 3600);
                }
                $result = $this->advertising_info($advplat,$type,$updatetime_automatic['updatetime_automatic']);
                Db::name('advplat')
                    ->where('id',$advplat['id'])
                    ->update($updatetime_automatic);
            }else{
                $result = '-1';
            }
        }
        return success('操作成功',$result);
    }

    public function advertising_info($advplat,$type,$updatetime_automatic = 0){
        if($type == 1){//核实昨天的广告
            $date_start = date('Y-m-d', strtotime('-1 days'));
        }elseif($type == 2){
            $date_start = $updatetime_automatic;
        }else{
            $date_start = date('Y-m-d', time());
        }
        $appsecret_proof = hash_hmac('sha256', $this->token,$this->client_secret);
        $appsecret_proof2 = hash_hmac('sha256', $this->token2,$this->client_secret2);
        $appsecret_proof3 = hash_hmac('sha256', $this->token3,$this->client_secret3);
        if(!empty($advplat['account'])){
            $account = explode(',', $advplat['account']);
        }else{
            $account = array();
        }
        $advertising_arr = array();
        $advertising_arr['cost'] = 0;
        if(!empty($account)){
            $arr_total = array();
            $success_num = 0;
            foreach ($account as $k=>$v) {
                if($type == 1){//核实昨天的广告
                    $url = 'https://graph.facebook.com/v18.0/act_'.$v.'/insights?access_token='.$this->token.'&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
                }else{
                    $url = 'https://graph.facebook.com/v18.0/act_'.$v.'/insights?access_token='.$this->token.'&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
                }
                $result = $this->geturl($url);
                $result = json_decode($result,true);
                //如果有错误就换第二个密钥
                if(!empty($result['error']['message']) && isset($result['error']['message'])){
                    if($type == 1){//核实昨天的广告
                        $url = 'https://graph.facebook.com/v18.0/act_'.$v.'/insights?access_token='.$this->token2.'&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof2;
                    }else{
                        $url = 'https://graph.facebook.com/v18.0/act_'.$v.'/insights?access_token='.$this->token2.'&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof2;
                    }
                    $result = $this->geturl($url);
                    $result = json_decode($result,true);
                }
                
                if(!empty($result['error']['message']) && isset($result['error']['message'])){
                    if($type == 1){//核实昨天的广告
                        $url = 'https://graph.facebook.com/v18.0/act_'.$v.'/insights?access_token='.$this->token3.'&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof3;
                    }else{
                        $url = 'https://graph.facebook.com/v18.0/act_'.$v.'/insights?access_token='.$this->token3.'&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof3;
                    }
                    $result = $this->geturl($url);
                    $result = json_decode($result,true);
                }
                // halt($result);
                
                if (!empty($result)) {

                    $arr = array();
                    $arr['date_start'] = '';
                    $arr['date_stop'] = '';
                    $arr['impressions'] = '';
                    $arr['spend'] = 0;
                    $arr['error'] = '';

                    if (!empty($result['data']) && isset($result['data'])) {
                        foreach ($result['data'] as $ka=>$va) {
                            $arr['advplat_id'] = $advplat['id'];
                            $arr['account_id'] = $va['account_id'];
                            $arr['date_start'] = $va['date_start'];
                            $date_start = $va['date_start'];
                            $arr['date_stop'] = $va['date_stop'];
                            $arr['impressions'] = $va['impressions'];
                            $arr['spend'] = $va['spend'];
                            $arr_total[] = $arr;
                            $success_num += 1;

                            $advertising_arr['cost'] += $va['spend'];
                            $advertising_arr['plat_account'] = $advplat['id'];
                            $advertising_arr['plat'] = $advplat['adv_id'];
                            $advertising_arr['admin_id'] = $advplat['admin_ids'];
                            $advertising_arr['create_time'] = date('Y-m-d 00:00:00',strtotime($va['date_start']));
                        }
                    }elseif(!empty($result['error']['message']) && isset($result['error']['message'])){
                        $arr['advplat_id'] = $advplat['id'];
                        $arr['account_id'] = $v;
                        $arr['date_start'] = $date_start;
                        $arr['error'] = $result['error']['message'];
                        $arr_total[] = $arr;
                    }elseif(empty($result['data'])){
                        $arr['advplat_id'] = $advplat['id'];
                        $arr['account_id'] = $v;
                        $arr['date_start'] = $date_start;
                        $arr_total[] = $arr;
                    }
                }
            }
        }
        //二次验证
        $test_api = table('advertisingapi')
                ->where('advplat_id', $advplat['id'])
                ->where('date_start',$date_start)
                ->find();
        if(!empty($test_api)){
            if(!empty($arr_total) && !empty($success_num)){
                table('advertisingapi')
                    ->where('advplat_id', $advplat['id'])
                    ->where('date_start',$date_start)
                    ->delete();
                table('advertisingapi')->insertAll($arr_total);
            }
        }else{
            table('advertisingapi')->insertAll($arr_total);
        }

        // 录入到手动花费
        if(!empty($advertising_arr['cost'])){
            $advertising_arr['type'] = 1;
            $type_advertising = table('advertising')
                ->where('plat_account', $advertising_arr['plat_account'])
                ->where('create_time',$advertising_arr['create_time'])
                ->where('type',0)
                ->find();
                //没有手动上传才能添加
            if(!empty($type_advertising)){
                $advertising_arr['status'] = 'hidden';
            }
            table('advertising')
                    ->where('plat_account', $advertising_arr['plat_account'])
                    ->where('create_time',$advertising_arr['create_time'])
                    ->where('type',1)
                    ->delete();
            table('advertising')->insert($advertising_arr);
        }
        return $success_num;
    }

    function geturl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    /**
    * 方法详情
    * @param array params
    */
    public function testads()
    {
        $appsecret_proof = hash_hmac('sha256', $this->token,$this->client_secret);
        $url = 'https://graph.facebook.com/v20.0/act_736486834720121/ads?access_token='.$this->token.'&fields=adlabels,adset_spec,adset_id,audience_id,bid_amount,conversion_domain,creative,creative_asset_groups_spec,date_format,display_sequence,engagement_audience,execution_options,include_demolink_hashes,name,priority,source_ad_id,status,tracking_specs&appsecret_proof='.$appsecret_proof;
        $result = $this->geturl($url);
        $result = json_decode($result,true);
        halt($result);
    }

    /**
    * 方法详情
    * @param array params
    */
    public function testcampaigns()
    {
        $appsecret_proof = hash_hmac('sha256', $this->token,$this->client_secret);
        $url = 'https://graph.facebook.com/v20.0/act_1416789828869011/campaigns?access_token='.$this->token.'&fields=name,objective&appsecret_proof='.$appsecret_proof;
        $result = $this->geturl($url);
        $result = json_decode($result,true);
        halt($result);
    }
    /**
    * 方法详情
    * @param array params
    */
    public function adcreatives()
    {
        $appsecret_proof = hash_hmac('sha256', $this->token,$this->client_secret);
        $url = 'https://graph.facebook.com/v20.0/act_1416789828869011/adcreatives?access_token='.$this->token.'&appsecret_proof='.$appsecret_proof;
        $result = $this->geturl($url);
        $result = json_decode($result,true);
        halt($result);
    }

    /**
    * 方法详情
    * @param array params
    */
    public function adcreativesinfo()
    {
        $appsecret_proof = hash_hmac('sha256', $this->token,$this->client_secret);
        $url = 'https://graph.facebook.com/v20.0/120209113576460637?access_token='.$this->token.'&fields=adlabels,bid_strategy,boosted_object_id,can_create_brand_lift_study,created_time,effective_status,lifetime_budget,name,objective,promoted_object,smart_promotion_type,source_campaign,special_ad_category,status,topline_id,account_id&appsecret_proof='.$appsecret_proof;
        $result = $this->geturl($url);
        $result = json_decode($result,true);
        halt($result);
    }
    
    public function campaigninfo()
    {
        $appsecret_proof = hash_hmac('sha256', $this->token,$this->client_secret);
        $url = 'https://graph.facebook.com/v20.0/120209713365060673?access_token='.$this->token.'&fields=adlabels,created_time,name,status,account_id&appsecret_proof='.$appsecret_proof;
        $result = $this->geturl($url);
        $result = json_decode($result,true);
        halt($result);
    }

    public function adinfo()
    {
        $appsecret_proof = hash_hmac('sha256', $this->token,$this->client_secret);
        $url = 'https://graph.facebook.com/v20.0/act_7403609273026635?access_token='.$this->token.'&fields=name&appsecret_proof='.$appsecret_proof;
        $result = $this->geturl($url);
        $result = json_decode($result,true);
        halt($result);
    }
    
}
